package demo.android.myapplication.demos.animation

import android.animation.Keyframe
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.animation.TypeEvaluator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.View
import cn.android.basic.centerX
import cn.android.basic.centerY
import cn.android.basic.sp
import kotlin.math.max
import kotlin.math.min

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/9 18:24
 */
val dataSource = arrayOf(
    "苹果",
    "香蕉",
    "橘子",
    "甜甜圈",
    "土豆",
    "西红柿",
    "面包",
    "汉堡",
    "三明治",
    "葡萄",
    "桃子",
    "栗子",
    "朱凯",
    "面条",
    "米饭",
    "馒头",
    "坚果",
    "口香糖",
    "芒果",
    "鸡蛋",
    "可乐",
    "雪碧",
    "EMP",
    "薯片",
    "电磁炮",
    "方便面",
    "冰淇淋",
    "马铃薯",
    "鸡腿",
    "莲藕",
)

fun dataSource(progress: Float): String{
    var index = (progress * dataSource.size).toInt()
    index = max(0, index)
    index = min(dataSource.lastIndex, index)
    return dataSource[index]
}

class StringAnimationView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    var text = dataSource[0]
    set(value) {
        field = value
        invalidate()
    }

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 26.sp
    }

    private val fm = Paint.FontMetrics()
    private val bounds = Rect()

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        val holder = PropertyValuesHolder.ofObject("text", StringTypeEvaluator(), dataSource.last())
        holder.setKeyframes(
            Keyframe.ofObject(0.0f, dataSource(0.0f)),
            Keyframe.ofObject(0.2f, dataSource(0.6f)),
            Keyframe.ofObject(0.8f, dataSource(0.8f)),
            Keyframe.ofObject(1.0f, dataSource(1.0f)),
        )
        val animator = ObjectAnimator.ofPropertyValuesHolder(this, holder)
        animator.startDelay = 1000
        animator.duration = 5000
        animator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.getFontMetrics(fm)
        paint.getTextBounds(text, 0, text.length, bounds)
        canvas.drawText(text, centerX - bounds.centerX(), centerY - (fm.ascent + fm.descent) / 2, paint)
    }
}

class StringTypeEvaluator: TypeEvaluator<String>{
    override fun evaluate(fraction: Float, startValue: String, endValue: String): String {
        val startIndex = dataSource.indexOf(startValue)
        val endIndex = dataSource.indexOf(endValue)
        val index:Int = ((endIndex - startIndex) * fraction + startIndex).toInt()
        Log.i("TAG-TEST", "index: $index , startIndex: $startIndex, endIndex: $endIndex, fraction: $fraction")
        return dataSource[min(index, dataSource.lastIndex)]
    }

}